<?php
namespace app\index\service;
/**
 * Class: OrderService
 * 订单服务类
 * Author: Jason ZHENG <mingjun.zheng@zengduokeji.com>
 * Date : 2018-09-11
 **/
use app\index\common;
use app\index\service\BaseService;
use think\Db;

class OrderService {
	/**
	 *  下架同步的商品，并给予标记
	 *  Jason
	 *  2018-09-11
	 **/
	public static function deSynchroProducts($product_id) {
		$synchroProducts = Db::table('product')->where(['source_product_id' => $product_id, 'state' => 0])->select();
		if ($synchroProducts != null) {
			Db::table('product')->where(['source_product_id' => $product_id, 'state' => 0])->update(['is_onsale' => 0, 'is_sold_business' => 1, 'product_state' => 6]);
			return true;
		}
	}

	public static function getBrandIds($brand_id) {
		if ($brand_id < 5) {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->whereor(['superior_id' => $brand_id])
				->whereor(['superior_gene' => ['like', $brand_id . "-%"]])
				->field('id')
				->select();
		} elseif ($brand_id > 4 && $brand_id < 42) {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->whereor(['superior_id' => $brand_id])
				->whereor(['superior_gene' => ['like', "%-" . $brand_id]])
				->whereor(['superior_gene' => ['like', "%-" . $brand_id . "-%"]])
				->field('id')
				->select();
		} elseif ($brand_id > 41 && $brand_id < 2686) {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->whereor(['superior_id' => $brand_id])
				->whereor(['superior_gene' => ['like', "%-" . $brand_id]])
				->field('id')
				->select();
		} else {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->field('id')
				->select();
		}

		$brand_ids = [];
		foreach ($brands as $brand) {
			$brand_ids[] = $brand['id'];
		}
		return $brand_ids;
	}

	/**
	 * 2018-06-01
	 * czw
	 * 验证产品是否存在订单
	 * @param type $product_id
	 */
	public static function check_order($product_id = 0, $business_id) {
		$order_info = Db::table('orders_info')->where(array('business_id' => $business_id, 'product_id' => $product_id, 'state' => 0))->find();
		if ($order_info && $order_info['status'] != 7 && $order_info['is_nursing'] != 1) {
			//存在订单 且 不是退货状态  且  非护理单
			$date = array('code' => 29999, 'msg' => '该产品已经售出，不能编辑或再售出', 'data' => array('product_id' => $product_id));
			exit(json_encode($date));
		}
	}

	/**
	 * 2018-06-01
	 * czw
	 * 计算商品利润
	 * @param type $type     计算类型   1：成交   2：退货退款    3:仅退款
	 * @param type $price   成交价/已支付价
	 * @param type $cost_price   成本价/采购价
	 * @param type $other_fee    额外费用
	 * @param type $refunded     已退款
	 * @return type
	 */

	public static function get_total_profit($type = 0, $price = 0, $cost_price = 0, $other_fee = 0, $nursing_fee = 0, $additional = 0, $refunded = 0, $shipping_fee = 0) {
		//成交订单    成交价-成本-额外费用  销售价格-采购价格-额外费用-护理费用-其他费用
		if ($type == 1) {
			$total_profit = (float) $price - (float) $cost_price - (float) $additional - (float) $other_fee - (float) $nursing_fee - (float) $shipping_fee;
		} elseif ($type == 2) {
			//退货        已支付-已退款-额外
			$total_profit = (float) $price - (float) $refunded - (float) $cost_price - (float) $other_fee - (float) $nursing_fee - (float) $additional - (float) $shipping_fee;
		} elseif ($type == 3) {
			//退款      已支付-已退款-额外
			$total_profit = (float) $price - (float) $refunded - (float) $other_fee - (float) $nursing_fee - (float) $additional - (float) $shipping_fee;
		} else {
			$total_profit = array('code' => 20300, 'msg' => '没有传计算商品利润的订单类型', 'data' => '');
		}
		return $total_profit;
	}

	/**
	 * 2018-06-01
	 * czw
	 * 计算商品实际利润
	 * @param type $type     计算类型   1：成交   2：退货退款    3:仅退款
	 * @param type $price   成交价/已支付价
	 * @param type $cost_price   成本价/采购价
	 * @param type $other_fee    额外费用
	 * @param type $refunded     已退款
	 * @return type
	 */
	public static function get_real_profit($price = 0, $cost_price = 0, $other_fee = 0, $nursing_fee = 0, $additional = 0, $refund = 0) {
		//        实际收入（定金）--采购价格-额外费用-护理费用-其他费用
		$real_profit = (float) $price - (float) $cost_price - (float) $additional - (float) $other_fee - (float) $nursing_fee - (float) $refund;
		return $real_profit;
	}

	/**
	 * 2018-06-01
	 * czw
	 * 验证是否存在手机号客户,如果没有则加为新客户
	 * @param type $phone
	 */
	public static function check_customer($phone = 0, $business_id) {
		common::check_mobile($phone);
		$user = Db::table('users')->where('phone', $phone)->find();
		if (!$user) {
			$user_id = Db::table('users')->insertGetId(array('phone' => $phone, 'is_customer' => 1, 'business_id' => $business_id));
			$user = Db::table('users')->where('id', $user_id)->find();
			$customerInsert = [
				'system_id' => $user['system_id'],
				'business_id' => $user['business_id'],
				'user_id' => $user_id,
				'createtime' => date('Y-m-d H:i:s'),
			];
			Db::table('customer')->insert($customerInsert);
		}
		return $user;
	}

	/**
	 * 2018-06-01
	 * czw
	 * 验证订单是否能完成
	 * @param type $status
	 * @param type $total_price
	 * @param type $deposit
	 */
	public static function is_complete($status = 0, $total_price = 0, $deposit = 0, $is_prepay = 0) {
		if ($is_prepay == 1) {
			$total_deposit = $deposit;
		} elseif ($is_prepay == 0) {
			$total_deposit = $total_price;
		}
		if ((float) $total_price - (float) $total_deposit > 0 && $status != 4) {
			exit(json_encode(array('code' => 29998, 'msg' => '支付金额不足，请将销售状态改为定金支付', 'data' => '')));
		}
	}

	/**
	 *  验证产品是否在可售状态
	 *  Jason
	 *  2018-09-08
	 **/
	public static function check_product_sale($product_id, $business_id) {
		$product_info = Db::table('product')->where(array('business_id' => $business_id, 'id' => $product_id, 'state' => 0))->find();
		if (!in_array($product_info['product_state'], [1, 2, 3, 4])) {
			$date = array('code' => 20067, 'msg' => '该产品不在可售状态', 'data' => '');
			exit(json_encode($date));
		}
	}
	/**
	 * [notice_add 添加通知消息]
	 * @DateTime 2018-09-13T13:57:56+0800
	 * @刘家腾
	 * @param    string                   $user_id     [用户ID]
	 * @param    string                   $type        [通知类型]
	 * @param    string                   $business_id [商户ID]
	 * @param    string                   $source_id   [对应的商品或订单id]
	 * @param    string                   $description [描述]
	 * @return   array                    $data        [返回值]
	 *
	 */
	public static function notice_add($user_id = '', $action_type = '0', $type = '', $business_id = '', $source_id = '', $description = '', $is_first = 1, $is_synchro = 0) {

		$insert_data = [
			'user_id' => $user_id,
			'business_id' => $business_id,
			'type' => $type,
			'source_id' => $source_id,
			'description' => $description,
			'is_first' => $is_first,
			'is_synchro' => $is_synchro,
			'action_type' => $action_type,
			'create_time' => date('Y-m-d H:i:s'),
		];
		$state = Db::table('announcement')->insertGetId($insert_data);
		if ($state == 0) {
			return ['code' => 30019, 'data' => $state, 'msg' => '插入失败！'];
		} else {

			return ['code' => 666, 'data' => $state, 'msg' => '插入成功！'];
		}
	}
	public static function check_issold_business($id = '', $peer_price = '') {
		$product_info = BaseService::product_info($id);

		if ($product_info['0']['is_synchro'] == 0 && $product_info['0']['peer_price'] < $peer_price) {
			$date = array('code' => 30066, 'msg' => '该产品已经入全网，同行价只可降低，不能增加', 'data' => '');
			exit(json_encode($date));
		}

	}
}
